package com.interceptor;

import com.common.stereotype.Token;
import com.common.ResultUtil;
import com.common.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Token token = method.getAnnotation(Token.class);
            if (null != token) {
                if (!TokenUtil.validToken(request)) {
                    /*重复提交*/
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/json;charset=utf-8");
                    StringBuffer sb0 = new StringBuffer("{\"status\": ").append(ResultUtil.REPEAT_SUBMIT).append(", \"message\": \"");
                    sb0.append("重复提交").append("\"}");
                    response.getWriter().write(sb0.toString());
                    return false;
                }
            }
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String token = (String) request.getAttribute(TokenUtil.TOKEN_NAME);
        if (StringUtils.isNotBlank(token)) {
            TokenUtil.setSessionToken(request, TokenUtil.TOKEN_NAME, token);
        }
        super.postHandle(request, response, handler, modelAndView);
    }

}
